package org.zoomdev.zoom.async.modules;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.aop.AopFactory;
import org.zoomdev.zoom.aop.annotations.NoEnhance;
import org.zoomdev.zoom.async.AsyncService;
import org.zoomdev.zoom.async.aop.AsyncMethodAopMaker;
import org.zoomdev.zoom.async.impl.AsyncServiceImpl;
import org.zoomdev.zoom.ioc.Ioc;
import org.zoomdev.zoom.ioc.annotations.Inject;
import org.zoomdev.zoom.ioc.annotations.IocBean;
import org.zoomdev.zoom.ioc.annotations.Module;
import org.zoomdev.zoom.ioc.annotations.ModuleInit;
import org.zoomdev.zoom.ioc.impl.factories.ModuleIocFactory;

@NoEnhance
@Module
public final class CoreAsyncModule implements ModuleIocFactory.ModuleInitialize {


    private static final Logger log = LoggerFactory.getLogger(CoreAsyncModule.class);

    @ModuleInit
    public void config(AopFactory factory, AsyncService asyncService) {
        factory.addFactory(new AsyncMethodAopMaker(asyncService), 0);
    }


    @IocBean
    public AsyncService getAsyncService(
            @Inject(config = "zoom.async.threadCount")
            int threadCount) {
        threadCount = threadCount == 0 ? Runtime.getRuntime().availableProcessors() : threadCount;
        log.info("Async service start ,thread count : {}",threadCount);
        return new AsyncServiceImpl(threadCount);
    }

    @Override
    public void initialize(Ioc ioc) {
        AsyncServiceImpl service = ioc.fetch(AsyncServiceImpl.class);
        ModuleIocFactory factory = ioc.fetch(ModuleIocFactory.class);
        factory.setExecutor(service.getExecutorService());
    }
}
